package com.runshu.newsmartark.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvent;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.runshu.newsmartark.R;
import com.runshu.newsmartark.adapter.ConfirmStockAdapter;
import com.runshu.newsmartark.base.MyApplication;
import com.runshu.newsmartark.dbutil.RefreshUtils;
import com.runshu.newsmartark.entity.ConfirmStockEntity;
import com.runshu.newsmartark.entity.InventoryEPCBean;
import com.runshu.newsmartark.mvp.contract.ConfirmStockContract;
import com.runshu.newsmartark.mvp.model.ConfirmStockModel;
import com.runshu.newsmartark.mvp.presenter.ConfirmStockPresenter;
import com.runshu.newsmartark.network.netbean.ResponseBean;
import com.runshu.newsmartark.reader.base.TakeStockBase;
import com.runshu.newsmartark.reader.helper.InventoryBuffer;
import com.runshu.newsmartark.util.MTagRealList;
import com.runshu.newsmartark.util.MacUtils;
import com.runshu.newsmartark.util.SoundPoolUtils;
import com.runshu.newsmartark.util.common.ToastUtils;
import com.runshu.newsmartark.util.widget.CommonShowDialog;
import com.runshu.newsmartark.util.widget.TopTitleBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Demo class
 *
 * @author yu
 * @date 2020/8/26
 * @decs：结算确认
 */

public class ConfirmStockActivity extends TakeStockBase implements ConfirmStockContract.View {

    private static final String TAG = "ConfirmStockActivity";

    @BindView(R.id.toolbar)
    TopTitleBar mToolbar;
    @BindView(R.id.tv_stock_num)
    TextView mTvStockNum;
    @BindView(R.id.tv_stock_change_num)
    TextView mTvStockChangeNum;
    @BindView(R.id.tv_user_name)
    TextView mTvUserName;
    @BindView(R.id.tv_user_keshi)
    TextView mTvUserKeshi;
    @BindView(R.id.recy_comfirm)
    RecyclerView mRecyComfirm;
    @BindView(R.id.tv_bot_chang_num)
    TextView mTvBotChangNum;
    @BindView(R.id.btn_sure)
    Button mBtnSure;
    @BindView(R.id.btn_not_sure)
    Button mBtnNotSure;
    private List<ConfirmStockEntity.AllProductsBean> mData;
    private ConfirmStockAdapter mAdapter;
    private ConfirmStockPresenter confirmStockPresenter;
    private CountDownTimer timerExit;
    private CountDownTimer timerShowPandian;
    //标识重新盘点用
    private String type;
    private ConfirmStockEntity confirmStockEntity;
    private Intent intent;
    private CommonShowDialog commonShowDialog;
    private MTagRealList mTagRealList;

//    // 语音合成对象
//    private SpeechSynthesizer mTts;

    @Override
    protected int getLayoutId() {
        return R.layout.act_comfirm_stock;
    }

    @Override
    protected void initView() {
//        // 初始化合成对象
//        mTts = SpeechSynthesizer.createSynthesizer(context, mTtsInitListener);
        mTagRealList = new MTagRealList();
        intent = getIntent();
        confirmStockPresenter = new ConfirmStockPresenter(this, new ConfirmStockModel());
        mToolbar.setIsShowBac(false);
        mToolbar.setTitle("结算确认");
        mData = new ArrayList<>();
        mAdapter = new ConfirmStockAdapter(mData);
        mRecyComfirm.setLayoutManager(new LinearLayoutManager(context));
        mRecyComfirm.setAdapter(mAdapter);
        mAdapter.bindToRecyclerView(mRecyComfirm);
        mAdapter.setEmptyView(R.layout.empty_confirm_view);
    }
    /**
     * 初始化监听。
     */
    private InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d(TAG, "InitListener init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                ToastUtils.showText("初始化失败,错误码："+code+",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
            } else {
                // 初始化成功，之后可以调用startSpeaking方法
                // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
                // 正确的做法是将onCreate中的startSpeaking调用移至这里

            }
        }
    };

    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
            //showTip("开始播放");
            //Log.d(TtsDemo.TAG,"开始播放："+ System.currentTimeMillis());
        }

        @Override
        public void onSpeakPaused() {
//            showTip("暂停播放");
        }

        @Override
        public void onSpeakResumed() {
//            showTip("继续播放");
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos,
                                     String info) {
            // 合成进度
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
            } else if (error != null) {
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            if (SpeechEvent.EVENT_SESSION_ID == eventType) {
                String sid = obj.getString(SpeechEvent.KEY_EVENT_AUDIO_URL);
                Log.d(TAG, "session id =" + sid);
            }

            //实时音频流输出参考
			/*if (SpeechEvent.EVENT_TTS_BUFFER == eventType) {
				byte[] buf = obj.getByteArray(SpeechEvent.KEY_EVENT_TTS_BUFFER);
				Log.e("MscSpeechLog", "buf is =" + buf);
			}*/
        }
    };
    @Override
    protected void onStart() {
        super.onStart();
    }


    @Override
    protected void initData() {
        countDownExit();
        SoundPoolUtils.play(context, R.raw.raw_jiesuan, 0);
        //倒计时
        if (timerExit != null) {
            timerExit.cancel();
        }
        countDownExit();
        confirmStockEntity = intent.getParcelableExtra("StockInfo");
        mTvStockNum.setText(String.valueOf(confirmStockEntity.getAllStock()));
        mTvUserName.setText(confirmStockEntity.getUserName());
        if (!TextUtils.isEmpty(confirmStockEntity.getOffice())) {
            mTvUserKeshi.setText(confirmStockEntity.getOffice());
        } else {
            mTvUserKeshi.setVisibility(View.GONE);
        }
        mTvStockChangeNum.setText(confirmStockEntity.getStockChange());
        mTvBotChangNum.setText(confirmStockEntity.getStockChange());
        mTvBotChangNum.setTextColor(confirmStockEntity.isAdd() ? context.getResources().getColor(R.color.color_FF1DD483) : context.getResources().getColor(R.color.color_F15555));
        mAdapter.setNewData(confirmStockEntity.getAllProducts());
        type = confirmStockEntity.getType();
//        //设置合成音量
//        mTts.setParameter(SpeechConstant.VOLUME,"100");
//        //设置合成语速
//        mTts.setParameter(SpeechConstant.SPEED, "49");
//        mTts.startSpeaking(confirmStockEntity.getStateStr()+"，请确认结算", mTtsListener);

    }

    @Override
    protected void bindListener() {

    }

    @Override
    protected void afterRequestPermission(int requestCode, boolean isAllGranted) {

    }


    @OnClick({R.id.btn_sure, R.id.btn_not_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_sure:
                //确认 插入数据库数据
                RefreshUtils.getInstance().refreshSelfProListAndRecord();
                if (timerExit != null) {
                    timerExit.cancel();
                }
                Intent intent = new Intent(context, MainActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_not_sure:
                //倒计时
                if (timerExit != null) {
                    timerExit.cancel();
                }
                mBtnSure.setText("确认 10s");
                startstop(true);
                showJieSuanDia();
                break;
        }
    }

    @Override
    public void OnGetConfirmStockSuccess(ResponseBean responseBean) {
        if (commonShowDialog != null) {
            commonShowDialog.dismiss();
            commonShowDialog.closeLoding();
        }
        SoundPoolUtils.play(context, R.raw.raw_jiesuan, 0);
        //倒计时
        if (timerExit != null) {
            timerExit.cancel();
        }
        countDownExit();
        ConfirmStockEntity confirmStockEntity = (ConfirmStockEntity) responseBean.pullData();
        mTvStockNum.setText(String.valueOf(confirmStockEntity.getAllStock()));
        mTvUserName.setText(confirmStockEntity.getUserName());
        mTvUserKeshi.setText(confirmStockEntity.getOffice());
        mTvStockChangeNum.setText(confirmStockEntity.getStockChange());
        mTvBotChangNum.setText(confirmStockEntity.getStockChange());
        mTvBotChangNum.setTextColor(confirmStockEntity.isAdd() ? context.getResources().getColor(R.color.color_FF1DD483) : context.getResources().getColor(R.color.color_F15555));
        mAdapter.setNewData(confirmStockEntity.getAllProducts());
        type = confirmStockEntity.getType();
//        //设置合成音量
//        mTts.setParameter(SpeechConstant.VOLUME,"100");
//        //设置合成语速
//        mTts.setParameter(SpeechConstant.SPEED, "49");
//        mTts.startSpeaking(confirmStockEntity.getStateStr()+"，请确认结算", mTtsListener);
    }

    @Override
    public void onError(String msg) {

        if (commonShowDialog != null)
            commonShowDialog.dismiss();
        commonShowDialog.closeLoding();
        ToastUtils.showText(msg);
    }

    /**
     * 倒计时显示退出
     */
    @SuppressLint("SetTextI18n")
    private void countDownExit() {
        timerExit = new CountDownTimer(11000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mBtnSure.setText("确认 " + millisUntilFinished / 1000 + "s");
                if (millisUntilFinished / 1000 >= 5) {
                    mBtnNotSure.setVisibility(View.GONE);
                } else {
                    mBtnNotSure.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onFinish() {
                //倒计时结束 插入数据库数据
               RefreshUtils.getInstance().refreshSelfProListAndRecord();
                Intent intent = new Intent(context, MainActivity.class);
                startActivity(intent);
            }
        }.start();
    }

    //结算中弹框
    private void showJieSuanDia() {
        commonShowDialog = new CommonShowDialog(context);
        commonShowDialog.setContent("正在结算中");
        commonShowDialog.setContentHint("请稍候...");
        commonShowDialog.setImgShow(R.mipmap.icon_jiesuan);
        commonShowDialog.show();
        commonShowDialog.setCancelable(false);
        commonShowDialog.showLoding();
    }


    @Override
    protected void onDestroy() {
        if (timerExit != null) {
            timerExit.cancel();
        }
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onScanResult(List<InventoryBuffer.InventoryTagMap> lsTagList) {
        super.onScanResult(lsTagList);
        mTagRealList.clear();
        mTagRealList.addAllData(lsTagList);
        if (commonShowDialog!=null){
            commonShowDialog.setContentHint("已盘点" + mTagRealList.size() + "件");
        }
        List<String> str = new ArrayList();
        for (int i = 0; i < mTagRealList.size(); i++) {
            str.add(mTagRealList.getData().get(i).strEPC.replace(" ", ""));
        }
        confirmStockPresenter.getConfirmStock(MacUtils.getFormatMacAddr(), MyApplication.getUserInfoGlob().getUsercode(), str, type);
    }
}